package com.liuya.session.listener;

import com.liuya.common.Constants;
import com.liuya.common.JedisUtil;
import com.liuya.session.service.SysSessionService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 会话监听器
 *
 * @author liuya
 * @date 20160823
 */
public class SessionListener implements HttpSessionListener {
    private Logger logger = LogManager.getLogger(SessionListener.class);

    @Autowired
    private SysSessionService sessionService;

    public void sessionCreated(HttpSessionEvent event) {
//        System.out.println(AopUtils.isAopProxy(sessionService));
//        System.out.println(AopUtils.isCglibProxy(sessionService));
//        System.out.println(AopUtils.isJdkDynamicProxy(sessionService));

        HttpSession session = event.getSession();
        session.setAttribute(Constants.WEBTHEME, "default");
        logger.info("创建了一个Session连接:[" + session.getId() + "]");
        setAllUserNumber(1);
    }

    public void sessionDestroyed(HttpSessionEvent event) {
//        System.out.println(AopUtils.isAopProxy(sessionService));
//        System.out.println(AopUtils.isCglibProxy(sessionService));
//        System.out.println(AopUtils.isJdkDynamicProxy(sessionService));
        HttpSession session = event.getSession();
        if (getAllUserNumber() > 0) {
            logger.info("销毁了一个Session连接:[" + session.getId() + "]");
        }
        session.removeAttribute(Constants.CURRENT_USER);
        sessionService.deleteBySessionId(session.getId());
        setAllUserNumber(-1);
    }

    private void setAllUserNumber(int n) {
        Long number = getAllUserNumber() + n;
        if (number >= 0) {
            logger.info("用户数：" + number);
            JedisUtil.set(Constants.ALLUSER_NUMBER, 60 * 60 * 24, number);
        }
    }

    /** 获取在线用户数量 */
    public static Long getAllUserNumber() {
        Object v = JedisUtil.get(Constants.ALLUSER_NUMBER);
        if (v != null) {
            return Long.valueOf(v.toString());
        }
        return 0L;
    }
}
